package com.xoa.service.vehicle;

import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.vehicle.VehicleMaintenanceMapper;
import com.xoa.dao.vehicle.VehicleMapper;
import com.xoa.dao.vehicle.VehicleUsageMapper;
import com.xoa.model.common.SysCode;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.users.Users;
import com.xoa.model.vehicle.VehicleMaintenanceWithBLOBs;
import com.xoa.model.vehicle.VehicleUsageExample;
import com.xoa.model.vehicle.VehicleUsageWithBLOBs;
import com.xoa.model.vehicle.VehicleWithBLOBs;
import com.xoa.service.users.UsersService;
import com.xoa.util.AjaxJson;
import com.xoa.util.CookiesUtil;
import com.xoa.util.GetAttachmentListUtil;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 创建作者:   高亚峰
 * 创建日期:   2017/9/20 10:36
 * 类介绍  :   车辆信息管理
 * 构造参数:
 */
@Service
public class VeHicleService {

    @Autowired
    private VehicleMapper vehicleMapper;
    @Autowired
    private SysCodeMapper sysCodeMapper;
    @Autowired
    private VehicleMaintenanceMapper vehicleMaintenanceMapper;
    @Autowired
    DepartmentMapper departmentMapper;

    @Autowired
    UsersService usersService;
    @Autowired
    VehicleUsageMapper usageMapper;


    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017/9/20 10:09
     * 类介绍  :   增加车辆
     * 构造参数:
     */
    public AjaxJson addVeHicle(HttpServletRequest request,VehicleWithBLOBs vehicleWithBLOBs){
        //从session中获取当前登录人的信息
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        String userId = users.getUserId();
        vehicleWithBLOBs.setvManage(userId);
        AjaxJson ajaxJson =new AjaxJson();
        ajaxJson.setSuccess(true);
        ajaxJson.setFlag(false);
        try {
            int i = vehicleMapper.insertSelective(vehicleWithBLOBs);
            if(i>0){
                ajaxJson.setMsg("ok");
                ajaxJson.setFlag(true);
            }
        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return ajaxJson;
    }

    public AjaxJson editVeHicle(VehicleWithBLOBs vehicleWithBLOBs){
        AjaxJson ajaxJson =new AjaxJson();
        ajaxJson.setSuccess(true);
        ajaxJson.setFlag(false);
        try {
            vehicleMapper.updateByPrimaryKeySelective(vehicleWithBLOBs);
                ajaxJson.setMsg("ok");
                ajaxJson.setFlag(true);
        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return ajaxJson;
    }
    public AjaxJson deleteVeHicleByVid(Integer vId){
        AjaxJson ajaxJson =new AjaxJson();
        ajaxJson.setSuccess(true);
        ajaxJson.setFlag(false);
        try {
            int i = vehicleMapper.deleteByPrimaryKey(vId);
            if(i>0){
                ajaxJson.setMsg("ok");
                ajaxJson.setFlag(true);
            }
        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return ajaxJson;
    }

    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017/9/20 10:49
     * 类介绍  :   批量删除车辆信息
     * 构造参数:
     */
    public AjaxJson deleteVeHiclesByVids(String[] vIds){
        AjaxJson ajaxJson =new AjaxJson();
        ajaxJson.setSuccess(true);
        ajaxJson.setFlag(false);
        try {
            vehicleMapper.deleteVeHiclesByVids(vIds);
            ajaxJson.setFlag(true);
            ajaxJson.setMsg("ok");
        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return ajaxJson;
    }
    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017/9/20 10:49
     * 类介绍  :   查询车辆详情
     * 构造参数:
     */
    public AjaxJson getDetailVeHicle(Integer vId){
        AjaxJson ajaxJson =new AjaxJson();
        ajaxJson.setSuccess(true);
        ajaxJson.setFlag(false);
        try {
            VehicleWithBLOBs vehicleWithBLOBs = vehicleMapper.selectByPrimaryKey(vId);
            if(vehicleWithBLOBs.getvDepart()!=null){
                String depart =vehicleWithBLOBs.getvDepart();
                if(!StringUtils.checkNull(depart)){
                    String depart1 =depart.substring(0,depart.length()-1);
                    vehicleWithBLOBs.setvDepartName(departmentMapper.getDeptNameById(Integer.valueOf(depart1)));
                }
            }
            if(!StringUtils.checkNull(vehicleWithBLOBs.getvOnwer())){
                String owner =vehicleWithBLOBs.getvOnwer();
                vehicleWithBLOBs.setoOnwerName(usersService.getUserNamesByUserIds(owner));
            }
            if(!StringUtils.checkNull(vehicleWithBLOBs.getvCaruser())){
                String carUser =vehicleWithBLOBs.getvCaruser();
                vehicleWithBLOBs.setvCaruserName(usersService.getUserNamesByUserIds(carUser));
            }
            if(!StringUtils.checkNull(vehicleWithBLOBs.getvDriver())){
                String [] drivers =vehicleWithBLOBs.getvDriver().split(",");
                StringBuffer vDriverName=new StringBuffer();
                for (String drivre:drivers
                     ) {
                    vDriverName.append(usersService.findUsersByuserId(drivre).getUserName()+",");
                }
                vehicleWithBLOBs.setvDriverName(vDriverName.toString());
            }
            if(!StringUtils.checkNull(vehicleWithBLOBs.getDeptRange())){
                String depart =vehicleWithBLOBs.getDeptRange();
                String[] de=depart.split(",");
                StringBuffer sb= new StringBuffer();
                for(String s:de){
                    String deptNameByDeptId = departmentMapper.getDeptNameByDeptId(Integer.valueOf(s));
                    sb.append(deptNameByDeptId+",");
                }
                vehicleWithBLOBs.setDeptRangeName(sb.toString());
            }
            if(!StringUtils.checkNull(vehicleWithBLOBs.getUserRange())){
                String driver =vehicleWithBLOBs.getUserRange();
                vehicleWithBLOBs.setUserRangeName(usersService.getUserNamesByUserIds(driver));
            }
            //设置车辆类型
            if (vehicleWithBLOBs.getvType() != null && vehicleWithBLOBs.getvType() !=""){
                SysCode sysCode = sysCodeMapper.getSingleCode("VEHICLETYPE", vehicleWithBLOBs.getvType());
                if(sysCode!=null){
                    vehicleWithBLOBs.setvTypeName(sysCode.getCodeName());
                }
            }else {
                vehicleWithBLOBs.setvTypeName("");
            }

            //设置车辆状态
            if (vehicleWithBLOBs.getvStatus()!=null && vehicleWithBLOBs.getvStatus()!=""){
                SysCode sysCode1 = sysCodeMapper.getSingleCode("VEHICLESTATE", vehicleWithBLOBs.getvStatus());
                if(sysCode1!=null){
                    vehicleWithBLOBs.setvStatusName(sysCode1.getCodeName());
                }
            }else {
                vehicleWithBLOBs.setvStatusName("");
            }
            if(!StringUtils.checkNull(vehicleWithBLOBs.getAttachmentId()) && !StringUtils.checkNull(vehicleWithBLOBs.getAttachmentName())){
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
                String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
                List<Attachment> list = GetAttachmentListUtil.returnAttachment(vehicleWithBLOBs.getAttachmentName(),vehicleWithBLOBs.getAttachmentId(),loginDateSouse,GetAttachmentListUtil.MODULE_VEHICLE);
                vehicleWithBLOBs.setAttachmentList(list);
            }

            ajaxJson.setObj(vehicleWithBLOBs);
            ajaxJson.setMsg("ok");
            ajaxJson.setFlag(true);
        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return ajaxJson;
    }
    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017/9/20 10:49
     * 类介绍  :   车辆信息列表详情
     * 构造参数:
     */
    public AjaxJson getAllVeHicle(HttpServletRequest request){
        AjaxJson ajaxJson =new AjaxJson();
        ajaxJson.setSuccess(true);
        ajaxJson.setFlag(false);

        List<VehicleUsageWithBLOBs> vehicleUsageWithBLOBs=new ArrayList<>();
        try {
            List<VehicleWithBLOBs> vehicleWithBLOBs = vehicleMapper.selectAllVeHicles();
            for (VehicleWithBLOBs vehicleWithBLOBs1:vehicleWithBLOBs){
                if(!StringUtils.checkNull(vehicleWithBLOBs1.getvDepart())){
                    String depart =vehicleWithBLOBs1.getvDepart();
                    if(!StringUtils.checkNull(depart)){
                        String depart1 =depart.substring(0,depart.length()-1);
                        vehicleWithBLOBs1.setvDepartName(departmentMapper.getDeptNameById(Integer.valueOf(depart1)));
                    }
                }
                if(!StringUtils.checkNull(vehicleWithBLOBs1.getvOnwer())){
                    String owner =vehicleWithBLOBs1.getvOnwer();
                    vehicleWithBLOBs1.setoOnwerName(usersService.getUserNamesByUserIds(owner));
                }
                if(!StringUtils.checkNull(vehicleWithBLOBs1.getvCaruser())){
                    String carUser =vehicleWithBLOBs1.getvCaruser();
                    vehicleWithBLOBs1.setvCaruserName(usersService.getUserNamesByUserIds(carUser));
                }
                if(!StringUtils.checkNull(vehicleWithBLOBs1.getvDriver())){
                    String driver =vehicleWithBLOBs1.getvDriver();
                    vehicleWithBLOBs1.setvDriverName(usersService.getUserNamesByUserIds(driver));
                }
                if(!StringUtils.checkNull(vehicleWithBLOBs1.getDeptRange())){
                    StringBuffer sb= new StringBuffer();
                    String depart =vehicleWithBLOBs1.getDeptRange();
                    if(StringUtils.checkNull(depart)){
                        String[] split = depart.split(",");
                        for(String s:split){
                            String deptNameByDeptId = departmentMapper.getDeptNameByDeptId(Integer.valueOf(s));
                            sb.append(deptNameByDeptId+",");
                        }
                    }
                    vehicleWithBLOBs1.setDeptRangeName(sb.toString());
                }
                if(!StringUtils.checkNull(vehicleWithBLOBs1.getUserRange())){
                    String driver =vehicleWithBLOBs1.getUserRange();
                    vehicleWithBLOBs1.setUserRangeName(usersService.getUserNamesByUserIds(driver));
                }
               //设置车辆类型
                if(vehicleWithBLOBs1.getvType() != null && vehicleWithBLOBs1.getvType() !=""){
                    SysCode sysCode = sysCodeMapper.getSingleCode("VEHICLETYPE", vehicleWithBLOBs1.getvType());
                    if(sysCode!=null){
                        vehicleWithBLOBs1.setvTypeName(sysCode.getCodeName());
                    }
                }else {
                    vehicleWithBLOBs1.setvTypeName("");
                }

                //设置车辆状态
                if (vehicleWithBLOBs1.getvStatus() != null &&vehicleWithBLOBs1.getvStatus() !=""){
                    //SysCode sysCode1 = sysCodeMapper.getSingleCode("VEHICLESTATE", vehicleWithBLOBs1.getvStatus());
                    VehicleUsageExample vehicleUsageExample=new VehicleUsageExample();
                    VehicleUsageExample.Criteria criteria = vehicleUsageExample.createCriteria();
                    criteria.andVIdEqualTo(vehicleWithBLOBs1.getvId().toString());
                    criteria.andDmerStatusEqualTo("1");
                    vehicleUsageWithBLOBs= usageMapper.selectByExampleWithBLOBs(vehicleUsageExample);
                    /*if(sysCode1!=null){
                        vehicleWithBLOBs1.setvStatusName(sysCode1.getCodeName());
                    }*/
                    if (vehicleUsageWithBLOBs.size() ==0) {
                        vehicleWithBLOBs1.setvStatusName("未使用");
                    }else{
                        vehicleWithBLOBs1.setvStatusName("已使用");
                    }
                }else {
                    vehicleWithBLOBs1.setvStatusName("");
                }

                 //车辆性质
                if (vehicleWithBLOBs1.getvNature() != null && vehicleWithBLOBs1.getvNature() != ""){
                    SysCode sysCode2 = sysCodeMapper.getSingleCode("PROPERTY", vehicleWithBLOBs1.getvNature());
                    if(sysCode2!=null){
                        vehicleWithBLOBs1.setvNatureName(sysCode2.getCodeName());
                    }
                }else {
                    vehicleWithBLOBs1.setvNatureName("");
                }

            }
            ajaxJson.setObj(vehicleWithBLOBs);
            ajaxJson.setMsg("ok");
            ajaxJson.setFlag(true);
        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return ajaxJson;
    }

    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017/9/21 10:49
     * 类介绍  :   车辆维护记录详情查看
     * 构造参数:
     */
    public AjaxJson getVeHicleFixRecord(Integer vId){
        AjaxJson ajaxJson =new AjaxJson();
        ajaxJson.setSuccess(true);
        ajaxJson.setFlag(false);
        try {
            List<VehicleMaintenanceWithBLOBs> recordByVid = vehicleMaintenanceMapper.getRecordByVid(vId);
            for( VehicleMaintenanceWithBLOBs vehicleMaintenanceWithBLOBs:recordByVid){
                //车牌号
                VehicleWithBLOBs vehicleWithBLOBs2 = vehicleMapper.selectByPrimaryKey(Integer.valueOf(vehicleMaintenanceWithBLOBs.getvId()));
                if(vehicleWithBLOBs2!=null){
                    vehicleMaintenanceWithBLOBs.setvIdNumber(vehicleWithBLOBs2.getvNum());
                }
                //维护类型
                SysCode sysCode = sysCodeMapper.getSingleCode("FIX_TYPE", vehicleMaintenanceWithBLOBs.getVmType());
                if(sysCode!=null){
                    vehicleMaintenanceWithBLOBs.setVmTypeName(sysCode.getCodeName());
                }
            }

            ajaxJson.setObj(recordByVid);
            ajaxJson.setMsg("ok");
            ajaxJson.setFlag(true);
        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return ajaxJson;
    }
    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017/9/22 10:49
     * 类介绍  :   获取车牌号下拉框
     * 构造参数:
     */
    public AjaxJson getDropDownBox(HttpServletRequest request){
        AjaxJson ajaxJson =new AjaxJson();
        ajaxJson.setSuccess(true);
        ajaxJson.setFlag(false);
        try {
            //从session中获取当前登录人的信息
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
            String userId = users.getUserId();
            Integer deptId = users.getDeptId();
            VehicleWithBLOBs vehicleWithBLOBs =new VehicleWithBLOBs();
            vehicleWithBLOBs.setUserRange(userId);
            vehicleWithBLOBs.setDeptRange(String.valueOf(deptId));
            List<VehicleWithBLOBs> allList =new ArrayList<VehicleWithBLOBs>();
            List<VehicleWithBLOBs> vehicleWithBLOBs1 = vehicleMapper.selectRangeVehicle(vehicleWithBLOBs);
            for(VehicleWithBLOBs vehicleWithBLOBs2:vehicleWithBLOBs1){
                allList.add(vehicleWithBLOBs2);
            }
            List<VehicleWithBLOBs> dropDownBox = vehicleMapper.getDropDownBox();
           for(VehicleWithBLOBs vehicleWithBLOBs2:dropDownBox){
               if((vehicleWithBLOBs2.getDeptRange()==null || vehicleWithBLOBs2.getDeptRange()=="")&&(vehicleWithBLOBs2.getUserRange()==null|| vehicleWithBLOBs2.getUserRange()=="")){
                   allList.add(vehicleWithBLOBs2);
               }
           }
            ajaxJson.setObj(allList);
            ajaxJson.setMsg("ok");
            ajaxJson.setFlag(true);
        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return ajaxJson;
    }
    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017/9/27 15:49
     * 类介绍  :   通过车牌号查询是否重复
     * 构造参数:
     */
    public AjaxJson getVeHicleByNum(String vNum){
        AjaxJson ajaxJson =new AjaxJson();
        ajaxJson.setSuccess(true);
        ajaxJson.setFlag(false);
        try {
            List<VehicleWithBLOBs> veHicleByvNum = vehicleMapper.getVeHicleByvNum(vNum);
            if(veHicleByvNum.size()>0){
                ajaxJson.setFlag(true);
                ajaxJson.setMsg("ok");
            }
        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg("err");
            e.printStackTrace();
        }
        return ajaxJson;
    }
    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017/9/27 15:49
     * 类介绍  :   通过车牌号查询是否在维修中
     * 构造参数:
     */

    public AjaxJson getVeHicleStatus(VehicleUsageWithBLOBs vehicleUsageWithBLOBs){
        AjaxJson ajaxJson =new AjaxJson();
        ajaxJson.setSuccess(true);
        ajaxJson.setFlag(false);
        try {
            String s = vehicleUsageWithBLOBs.getvId();
            if(s!=null &&s!=""){
                List<VehicleMaintenanceWithBLOBs> veHicleStatus = vehicleMaintenanceMapper.getVeHicleStatus(Integer.valueOf(s));
                if(veHicleStatus!=null){
                    for(VehicleMaintenanceWithBLOBs vehicleMaintenanceWithBLOBs:veHicleStatus){
                        Date date =vehicleMaintenanceWithBLOBs.getVmRequestDate();
                        Date vuStart = vehicleUsageWithBLOBs.getVuStart();
                        Date vuEnd=vehicleUsageWithBLOBs.getVuEnd();
                        long time = date.getTime();
                        long startTime = vuStart.getTime();
                        long endTime= vuEnd.getTime();
                        if(startTime<=time&&endTime>=time){
                            ajaxJson.setFlag(true);
                            ajaxJson.setMsg("申请该车时段在维护中");
                        }
                    }
                }
            }
        } catch (Exception e) {
            ajaxJson.setFlag(false);
            ajaxJson.setMsg("err");
            e.printStackTrace();
        }
        return ajaxJson;
    }
}
